package leetcode.top100;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ：zsy
 * @date ：Created 2022/10/22 8:54 PM
 * @description：https://leetcode.cn/problems/3sum/
 */
public class _015_三数之和 {
    @Test
    public void test() {

    }

    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> ans = new ArrayList<>();
            Arrays.sort(nums);
            int n = nums.length;
            for (int first = 0; first < n - 2; first++) {
                if (first > 0 && nums[first] == nums[first - 1]) continue;
                int third = n - 1;
                int target = -nums[first];
                for (int second = first + 1; second < n - 1; second++) {
                    if (second > first + 1 && nums[second] == nums[second - 1]) continue;
                    while (second < third && nums[second] + nums[third] > target) {
                        third--;
                    }
                    if (third == second) break;
                    if (nums[second] + nums[third] == target) {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[first]);
                        list.add(nums[second]);
                        list.add(nums[third]);
                        ans.add(list);
                    }
                }
            }
            return ans;
        }
    }
}
